package com.gaoxin.api.Interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gaoxin.api.filter.BodyReaderHttpServletRequestWrapper;
import com.gaoxin.api.util.SignUtil;
import com.gaoxin.common.exception.RRException;

public class SignInterceptor implements HandlerInterceptor {

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String requestMethord = request.getRequestURI();// 请求方法
		if (requestMethord == null) {
			return false;
		}

		if (!MediaType.APPLICATION_JSON_VALUE.equalsIgnoreCase(request.getHeader(HttpHeaders.CONTENT_TYPE))) {
			return true;
		}

		// 获取请求参数
		JSONObject parameterMap = JSON
				.parseObject(new BodyReaderHttpServletRequestWrapper(request).getBodyString(request));
		String reqdata = parameterMap.getString("data");
		if (StringUtils.isBlank(reqdata)) {
			return true;
		}
		String channelid = parameterMap.getString("channelid");
		if (StringUtils.isBlank(channelid)) {
			throw new RRException("渠道编号不能为空");
		}
		String sign = parameterMap.getString("sign");
		if (StringUtils.isBlank(sign)) {
			throw new RRException("签名不能为空");
		}

		JSONObject reqDataObject = JSON.parseObject(reqdata);
		// 获取渠道秘密

		// 验证签名数据
		boolean verifyFlag = SignUtil.verifyPaySign(reqDataObject, sign, "909090909099");
		if (!verifyFlag) {
			throw new RRException("数据签名异常");
		}
		return true;
	}
}
